package com.qinggeng.framework.config.mq.impl;

import com.alibaba.fastjson.JSON;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.OrdersStatusEnum;
import com.qinggeng.common.enums.PayStatusEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.framework.config.mq.MQSendUtils;
import com.qinggeng.framework.config.mq.dto.MessageOrdersDTO;
import com.qinggeng.framework.config.mq.dto.MessageOrdersMessageDTO;
import com.qinggeng.framework.config.mq.enums.MQTypeEnum;
import com.qinggeng.framework.config.mq.handle.MessageHandle;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.mapper.OrdersGoodsMapper;
import com.qinggeng.project.system.service.IGoodsKeepService;
import com.qinggeng.project.system.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class OrdersPayOutTimeHandleImpl implements MessageHandle {
    private final static String KEEP_OF_GOODS = "keepOfGoods:";

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private MQSendUtils mqSendUtils;

    @Autowired
    private IGoodsKeepService goodsKeepService;


    @Override
    public void handle(String msg) {

        log.info("订单支付超时处理{}"+msg);

        MessageOrdersDTO ordersDTO= JSON.parseObject(msg,MessageOrdersDTO.class);
        Orders orders=ordersService.selectOrdersByOrdersNo(ordersDTO.getOrdersNo());
        if(null==orders){
            throw new CustomException("订单不存在");
        }
        if(!orders.getStatus().equals(OrdersStatusEnum.进行中.getValue())){
            return;
        }
        if(!orders.getPayStatus().equals(PayStatusEnum.未支付.getValue())){
            return;
        }
        orders.setStatus(OrdersStatusEnum.已关闭.getValue());
        orders.setPayStatus(PayStatusEnum.已超时.getValue());
        int rows=ordersService.updateOrders(orders);
        if(rows<1){
            throw new CustomException("订单关闭失败！");
        }
        //恢复库存
        goodsKeepService.addKeepNum(orders);
        //发送消息，保存
        MessageOrdersMessageDTO ordersMessageDTO = new MessageOrdersMessageDTO();
        ordersMessageDTO.setType(MQTypeEnum.ORDERS_MESSAGE_JPUSH.getType());
        ordersMessageDTO.setUserType(UserTypeEnum.MEMBER.getCode());
        ordersMessageDTO.setOrdersNo(orders.getOrdersNo());
        ordersMessageDTO.setMark("支付超时通知");
        ordersMessageDTO.setMessage("尊敬的用户,您的订单" + orders.getOrdersNo() + "支付超时关闭!");
        mqSendUtils.sendAsynMessage(ordersMessageDTO);
    }
}
